package com.example.yuimagesearchmcp.tool;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.ai.tool.annotation.Tool;
import org.springframework.ai.tool.annotation.ToolParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service
public class ImageSearchTool {

//    @Value("MKKrDghbSqbZn5T0oUIB11FadO23xIjKCB2mLtSEioi2aMCLgbnHZtsE") //Pexels API 密钥（从官网去申请）
    private String API_KEY="MKKrDghbSqbZn5T0oUIB11FadO23xIjKCB2mLtSEioi2aMCLgbnHZtsE";

    //Pexels 常规搜索接口 https://www.pexels.com/zh-cn/api/documentation#photos-search
    private static final String API_URL = "https://api.pexels.com/v1/search";

    @Tool(description = "search image from web")
    public String searchImage(@ToolParam(description = "search query keyword") String query) {
        try {
            //将列表转换成字符串
            return String.join(",", searchMediumImage(query));
        } catch (Exception e) {
            return "Error search image: " + e.getMessage();
        }
    }

    //获取搜索结果中的中等尺寸图片列表
    private List<String> searchMediumImage(String query) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", API_KEY);

        //添加请求参数
        Map<String, Object> params = new HashMap<>();
        params.put("query", query);

        String response = HttpUtil.createGet(API_URL).addHeaders(headers).form(params).execute().body();


        return JSONUtil.parseObj(response)
                .getJSONArray("photos")
                .stream()
                .map(photoObj -> (JSONObject) photoObj)
                .map(photoObj -> photoObj.getJSONObject("src"))
                .map(photo -> photo.getStr("medium"))
                .filter(StrUtil::isNotBlank)
                .collect(Collectors.toList());
    }
}



